<template>
  <div>
    <!-- 题目头部信息 -->
    <QuestionHeader 
      :test="test" 
      :question="question" 
      :is-edit="isEdit" 
      :readonly="readonly" 
      :show-up-down="isShowTestUpOrDown()" 
      :up-disabled="testUpDisabled" 
      :down-disabled="testDownDisabled"
      @edit="isEdit = true"
      @save-continue="saveQuestion(true)"
      @bind-question="bindQuestion()"
      @question-up="testQuestionUp"
      @question-down="testQuestionDown"
    />

    <el-row :gutter="20">
      <el-col :span="16">
        <!-- 父题目信息 -->
        <el-card v-if="parentQuestion.id" class="box-card">
          <div slot="header" class="clearfix">
            <span>
              主题目
              <el-tag effect="dark" size="mini">{{ parentQuestion.name ? parentQuestion.name : questionType[parentQuestion.type] }}</el-tag>
            </span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="goBack()">返回主题目</el-button>
          </div>
          <div style="width: 90%; margin-left: 5%; margin-top: 5px">
            <katex :katex-content="parentQuestion.title" index="parentQuestionTitle" />
          </div>
          <div style="width: 90%; margin-left: 5%; margin-top: 5px">
            <katex :katex-content="parentQuestion.materials" index="parentQuestionMaterials" />
          </div>
        </el-card>

        <!-- 主题目编辑区域 -->
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <el-row v-if="question.id && !test.id" :gutter="20" class="cardHeader" style="display: flex">
              <el-col style="flex: 1" />
              <el-col v-if="question.id && !test.id" class="cardHeader" style="width: 250px; margin-top: 4px">
                <el-button :disabled="questionUpDisabled" size="mini" class="flbtn" icon="el-icon-arrow-up" circle @click="questionUp" />
                <el-button :disabled="questionDownDisabled" size="mini" class="flbtn" icon="el-icon-arrow-down" circle @click="questionDown" />
              </el-col>
            </el-row>
            <el-row v-if="!question.readonly && !isEdit" :gutter="20" class="cardHeader" style="display: flex">
              <el-col style="flex: 1" />
              <el-col v-if="question.id && !test.id" class="cardHeader" style="width: 250px; margin-top: 4px">
                <el-button class="flbtn" size="small" type="primary" @click="isEdit = true">编辑</el-button>
              </el-col>
            </el-row>
          </div>
          <div class="content">
            <!-- 基本信息表单 -->
            <QuestionBasicForm 
              ref="questionForm"
              :question="question" 
              :readonly="readonly" 
              :subject-options="subjectOptions" 
              :question-type="questionType"
              :rules="rules"
              @subject-change="queryPoint"
              @title-change="handleTitleChange"
              @type-change="changeQuestionType"
            />

            <!-- 题目答案区域 -->
            <QuestionAnswer 
              :question="question" 
              :readonly="readonly" 
              :select-answer="selectAnswer"
              :ai-analyze-loading="aiAnalyzeLoading"
              @answer-change="handleAnswer"
              @ai-analyze="handleAiAnalyze"
            />

            <!-- 知识点管理 -->
            <KnowledgePointManager 
              :knowledge-points="knowledgePoints" 
              :readonly="readonly" 
              :knowledge-point-options="knowledgePointOptions"
              :question="question"
              :parent-question="parentQuestion"
              @add-knowledge-point="addKnowledgePointToList"
              @remove-knowledge-point="handleClose"
              @update-sort="updateSort"
            />

            <!-- 操作按钮 -->
            <el-form-item>
              <el-button v-if="!readonly" type="info" @click="saveQuestion(false)">暂存</el-button>
              <el-button v-if="!readonly" type @click="saveQuestion(true)">暂存并继续添加</el-button>
            </el-form-item>
          </div>
        </el-card>

        <!-- 子题目管理 -->
        <SubQuestionManager 
          :question="question" 
          :son-questions="sonQuestions" 
          :readonly="readonly" 
          :question-type="questionType"
          @add-sub-question="saveSonQuestion()"
          @edit-sub-question="sonQuestionInfo"
          @delete-sub-question="deleteQuestion"
          @update-sort-question="updateSortQuestion"
        />
      </el-col>

      <!-- 预览区域 -->
      <el-col :span="8">
        <el-card class="phoneShow">
          <div class="phoneContent">
            <phone :question="questionShow" :parent-question="parentQuestionShow" :knowledge-points="knowledgePoints" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- AI功能组件 -->
    <AIFeatures 
      ref="aiFeatures"
      :question="question" 
      :parent-question="parentQuestion" 
      :question-type="questionType"
      @adopt-answer="adoptAiAnswer"
      @adopt-analyze="adoptAiAnalyze"
    />
  </div>
</template>

<script>
// 导入子组件
import QuestionHeader from './components/QuestionHeader.vue';
import QuestionBasicForm from './components/QuestionBasicForm.vue';
import QuestionAnswer from './components/QuestionAnswer.vue';
import KnowledgePointManager from './components/KnowledgePointManager.vue';
import SubQuestionManager from './components/SubQuestionManager.vue';
import AIFeatures from './components/AIFeatures.vue';

// 导入其他组件
import phone from "@/components/phone";
import katex from "@/components/phone/katex";

// 导入API
import { addQuestionToTest, getquestionScore } from "@/api/test.js";
import {
  searchPoint,
  queryQuestionPoint,
  saveQuestionPoint,
  deleteQuestionPoint,
  questionPointSort,
} from "@/api/point.js";
import {
  questionList,
  saveQuestion,
  questionInfo,
  deleteQuestion,
  questionSort,
  saveQuestionInfoLog,
  questionUpAndDown,
} from "@/api/question.js";
import { getSubjectList } from "@/api/subjectType.js";

export default {
  name: "QuestionInfoOptimized",
  components: {
    QuestionHeader,
    QuestionBasicForm,
    QuestionAnswer,
    KnowledgePointManager,
    SubQuestionManager,
    AIFeatures,
    phone,
    katex,
  },
  data() {
    return {
      // 基础数据
      testQuestionIdList: [],
      aiAnalyzeLoading: false,
      rules: {
        subjectId: [{ required: true, message: "科目必填" }],
      },
      loading: false,
      questionShow: {},
      parentQuestionShow: {},
      knowledgePointOptions: [],
      knowledgePoints: [],
      sonQuestions: [],
      selectAnswer: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"],
      questionType: {
        1: "单选题",
        2: "多选题",
        3: "判断题",
        4: "填空",
        5: "简答题",
        6: "材料题",
        7: "连线题",
      },
      test: {
        id: null,
      },
      isEdit: false,
      parentQuestion: {
        id: null,
        title: "",
      },
      question: {
        id: null,
        testStructure: "",
        blankSum: 1,
        select: [
          { select: "A", content: "" },
          { select: "B", content: "" },
          { select: "C", content: "" },
          { select: "D", content: "" },
        ],
        options: {
          left: [
            { index: 1, content: '' },
            { index: 2, content: '' },
            { index: 3, content: '' }
          ],
          right: [
            { index: 1, content: '' },
            { index: 2, content: '' },
            { index: 3, content: '' }
          ]
        },
        answer: [],
        score: 1,
        type: "1",
        title: "",
        analyze: "",
        difficultyLevel: 1,
        questionType: 1,
        isOfficialQuestion: 0,
        officialQuestionSource: "",
        year: "",
        subjectId: "",
      },
      questionUpDisabled: true,
      questionDownDisabled: true,
      testQuestionList: [],
      subjectOptions: [],
    };
  },
  computed: {
    testUpDisabled() {
      let index = this.testQuestionIdList.indexOf(this.question.id);
      return index == 0;
    },
    testDownDisabled() {
      let index = this.testQuestionIdList.indexOf(this.question.id);
      return index == this.testQuestionIdList.length - 1;
    },
    readonly() {
      return (!this.isEdit || this.question.readonly) && this.question.id != null;
    },
  },
  watch: {
    question: {
      handler(newValue) {
        this.questionShow = this.question;
        this.parentQuestionShow = this.parentQuestion;
      },
      deep: true,
    },
    parentQuestion: {
      handler() {
        this.parentQuestionShow = this.parentQuestion;
      },
      deep: true,
    },
  },
  created() {
    this.initializeComponent();
  },
  methods: {
    // 初始化组件
    initializeComponent() {
      // 初始化连线题选项
      if (!this.question.options.left || this.question.options.left.length === 0) {
        this.question.options.left = JSON.parse(JSON.stringify([
          { index: 1, content: '' },
          { index: 2, content: '' },
          { index: 3, content: '' }
        ]));
      }
      if (!this.question.options.right || this.question.options.right.length === 0) {
        this.question.options.right = JSON.parse(JSON.stringify([
          { index: 1, content: '' },
          { index: 2, content: '' },
          { index: 3, content: '' }
        ]));
      }
      
      // 初始化路由参数
      const test = this.$router.currentRoute.params.test;
      this.test = this.$router.currentRoute.params.test || this.test;
      
      if (this.test && this.test.testStructures) {
        this.test.testStructures.forEach((element) => {
          if (element.question) {
            element.question.forEach((res) => {
              this.testQuestionIdList.push(res.questionId);
              this.testQuestionList.push({
                questionId: res.questionId,
                score: res.score,
                testStructureId: element.id,
              });
            });
          }
        });
      }
      
      if (this.test.id) {
        this.question.testId = this.test.id;
        this.question.isOfficialQuestion = 1;
        this.question.officialQuestionSource = this.test.title;
        this.question.year = this.test.year;
      }
      
      if (this.$router.currentRoute.params.question) {
        this.question.id = this.$router.currentRoute.params.question.id;
        this.question.score = this.$router.currentRoute.params.question.score;
      }
      
      this.getSubject();
      this.questionInfo();
      this.getQuestionUpAndDown();
    },

    // 获取科目列表
    async getSubject() {
      try {
        const res = await getSubjectList();
        this.subjectOptions = res.data || [];
      } catch (error) {
        console.error('获取科目列表失败:', error);
      }
    },

    // 查询知识点
    queryPoint() {
      if (this.question.subjectId && this.question.subjectId.length > 0) {
        const subjectId = this.question.subjectId[this.question.subjectId.length - 1];
        searchPoint(subjectId).then((res) => {
          this.knowledgePointOptions = res.data || [];
        });
      }
    },

    // 获取题目信息
    questionInfo() {
      if (this.question.id) {
        questionInfo(this.question.id).then((res) => {
          if (res.data) {
            Object.assign(this.question, res.data);
            this.queryPoint();
            this.queryQuestionPoint();
            this.getSonQuestion();
          }
        });
      }
    },

    // 查询题目知识点
    queryQuestionPoint() {
      if (this.question.id) {
        queryQuestionPoint(this.question.id).then((res) => {
          this.knowledgePoints = res.data || [];
        });
      }
    },

    // 获取子题目
    getSonQuestion() {
      if (this.question.id && this.question.type === '6') {
        questionList({ parentId: this.question.id }).then((res) => {
          this.sonQuestions = res.data || [];
        });
      }
    },

    // 题目类型改变
    changeQuestionType() {
      this.question.options = {};
      if (['1', '2', '3', '4', '7'].includes(this.question.type)) {
        this.question.answer = [];
      }
      if (this.question.type == 3) {
        this.question.select = [
          { select: "A", content: "对" },
          { select: "B", content: "错" }
        ];
      }
      if (this.question.type === '7') {
        this.question.options = {
          left: [
            { content: '', index: 1 },
            { content: '', index: 2 },
            { content: '', index: 3 }
          ],
          right: [
            { content: '', index: 1 },
            { content: '', index: 2 },
            { content: '', index: 3 }
          ]
        };
      }
    },

    // 处理答案变化
    handleAnswer() {
      // 答案变化处理逻辑
    },

    // 处理标题变化
    handleTitleChange(value) {
      // 标题变化处理逻辑
    },

    // AI解析处理
    handleAiAnalyze() {
      this.aiAnalyzeLoading = true;
      this.$refs.aiFeatures.showAiAnalyze();
      this.aiAnalyzeLoading = false;
    },

    // 采纳AI答案
    adoptAiAnswer(answer) {
      this.$set(this.question, 'answer', answer);
    },

    // 采纳AI解析
    adoptAiAnalyze(analyze) {
      this.question.analyze = analyze;
    },

    // 添加知识点到列表
    addKnowledgePointToList(point) {
      if (this.knowledgePoints) {
        this.knowledgePoints.push(point);
      } else {
        this.knowledgePoints = [point];
      }
    },

    // 移除知识点
    handleClose(knowledgePoint) {
      const index = this.knowledgePoints.findIndex(point => point.id === knowledgePoint.id);
      if (index > -1) {
        this.knowledgePoints.splice(index, 1);
      }
    },

    // 更新知识点排序
    updateSort() {
      // 知识点排序逻辑
    },

    // 更新子题目排序
    updateSortQuestion() {
      // 子题目排序逻辑
    },

    // 保存题目
    saveQuestion(continueAdd) {
      this.$refs.questionForm.validate().then(() => {
        // 保存逻辑
        saveQuestion(this.question).then((res) => {
          if (res.code === 0) {
            this.$message.success('保存成功');
            if (continueAdd) {
              // 继续添加逻辑
            }
          }
        });
      }).catch(() => {
        this.$message.error('请检查必填项');
      });
    },

    // 保存子题目
    saveSonQuestion() {
      // 保存子题目逻辑
    },

    // 子题目信息
    sonQuestionInfo(id) {
      this.$router.push({
        path: '/questionInfo',
        params: {
          question: { id },
          test: this.test,
        },
      });
    },

    // 删除题目
    deleteQuestion(id) {
      this.$confirm('确认删除该题目?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteQuestion(id).then((res) => {
          if (res.code === 0) {
            this.$message.success('删除成功');
            this.getSonQuestion();
          }
        });
      });
    },

    // 绑定题目
    bindQuestion() {
      // 绑定题目逻辑
    },

    // 返回主题目
    goBack() {
      this.$router.go(-1);
    },

    // 题目上移
    testQuestionUp() {
      let index = this.testQuestionIdList.indexOf(this.question.id);
      this.question.id = this.testQuestionIdList[index - 1];
      let testQuestion = this.testQuestionList.find(
        (res) => res.questionId == this.question.id
      );
      this.question.score = testQuestion.score;
      this.test.testStructure = testQuestion.testStructureId;
      this.questionInfo();
    },

    // 题目下移
    testQuestionDown() {
      let index = this.testQuestionIdList.indexOf(this.question.id);
      this.question.id = this.testQuestionIdList[index + 1];
      let testQuestion = this.testQuestionList.find(
        (res) => res.questionId == this.question.id
      );
      this.question.score = testQuestion.score;
      this.test.testStructure = testQuestion.testStructureId;
      this.questionInfo();
    },

    // 题目上移（非试卷）
    questionUp() {
      // 题目上移逻辑
    },

    // 题目下移（非试卷）
    questionDown() {
      // 题目下移逻辑
    },

    // 获取题目上下移动状态
    getQuestionUpAndDown() {
      // 获取上下移动状态逻辑
    },

    // 是否显示试卷题目上下移动
    isShowTestUpOrDown() {
      return this.test.id && this.question.id;
    },
  },
};
</script>

<style scoped>
.phoneShow {
  position: sticky;
  top: 20px;
}

.phoneContent {
  padding: 20px;
}

.content {
  padding: 20px;
}

.flbtn {
  margin-right: 10px;
}

.cardHeader {
  display: flex;
  align-items: center;
}
</style>